package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.flow.util.FlowUpdateAuditUtil;
import com.softer.wxzj.common.logic.CalculateAmount;
import com.softer.wxzj.common.logic.DepReqLogic;
import com.softer.wxzj.common.logic.ExpReqLogic;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseHouseInfoService;
import com.softer.wxzj.service.DepModeInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.softer.wxzj.common.util.OperUtil.zoneCodeUtil;

/**
 * @description:房屋信息
 * @ClassName: BaseHouseInfoServiceImpl
 * @author: zcz
 * @date: 2019-05-20 16:3
 */
@Service
@Slf4j
public class BaseHouseInfoServiceImpl implements BaseHouseInfoService {

    @Autowired
    BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private FlowUpdateAuditUtil flowUpdateAuditUtil;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private ModifyUtil<BaseHouseInfo> modifyUtil;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private BaseOwnerInfoMapper baseOwnerInfoMapper;
    @Autowired
    private BaseBuildModifyDetailMapper baseBuildModifyDetailMapper;
    @Autowired
    private CombineEntityUtil<BaseHouseInfo> combineEntityUtil;
    @Autowired
    BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    ZoneCodeMapper zoneCodeMapper;
    @Autowired
    DicContentMapper dicContentMapper;
    @Autowired
    DepModeInfoMapper depModeInfoMapper;
    @Autowired
    private RefReqMapper refReqMapper;
    @Autowired
    private BaseBankInfoMapper baseBankInfoMapper;
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private DepReqListInfoMapper depReqListInfoMapper;
    @Autowired
    RefReqListMapper refReqListMapper;
    @Autowired
    private CalculateAmount calculateAmount;
    @Autowired
    private AccTransactionLogMapper accTransactionLogMapper;
    @Autowired
    ExpPayReqMapper expPayReqMapper;
    @Autowired
    private BaseOwnerInfoServiceImpl baseOwnerInfoService;
    @Autowired
    private BaseCellInfoMapper baseCellInfoMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private DepReqLogic depReqLogic;
    @Autowired
    private ExpReqLogic expReqLogic;
    @Autowired
    private RefReqServiceImpl refReqServiceImpl;
    @Autowired
    private SplitMergeServiceImpl splitMergeService;
    @Autowired
    private BaseSubRegionInfoMapper baseSubRegionInfoMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private BaseModifyReqServiceImpl baseModifyReqServiceImpl;
    @Autowired
    private ExpProjectReqMapper expProjectReqMapper;
    @Autowired
    private BaseModifyDetailServiceImpl baseModifyDetailService;
    @Autowired
    private DepModeInfoService depModeInfoService;
    @Autowired
    private FileServiceImpl fileService;

    @Override
    public CommonResult insert(BaseHouseInfo baseHouseInfo) {
        String id = UUIDUtil.getUUID();
        baseHouseInfo.setId(id);
        baseHouseInfo.setCreater(ShiroUserUtil.getUserName());
        int num = baseHouseInfoMapper.insert(baseHouseInfo);
        return CommonResult.idResult(num, id);
    }

    private String changHouse(BaseHouseInfo baseHouseInfo) {
        String houseSite = "";
        BaseHouseInfo b = baseHouseInfoMapper.getInfo(baseHouseInfo.getId());
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(b.getBuildNo());
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(baseRegionInfo.getZoneCode(), 0, 6));
        BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(b.getCellNo());
        //baseHouseInfo.setState(NumberEnum.ZERO.getNum() + "");
        //房屋坐落 区+小区名+自然幢名+单元名
        if (StringUtils.isBlank(baseBuildInfo.getSubRegionName())) {
            baseBuildInfo.setSubRegionName("");
        }
        houseSite = zoneName + baseRegionInfo.getRegionName() + baseBuildInfo.getSubRegionName() + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + baseHouseInfo.getRoomName();
        return houseSite;
    }

    @Override
    public CommonResult update(BaseHouseInfo baseHouseInfo) {
        baseHouseInfo.setUpdateTime(DateUtils.getNow());
        baseHouseInfo.setModifier(ShiroUserUtil.getUserName());
        //拼接房屋信息
        //String houseSite=  changHouse(baseHouseInfo);
        // baseHouseInfo.setHouseSite(houseSite);
        BaseHouseInfo info = baseHouseInfoMapper.getInfo(baseHouseInfo.getId());
        if (info != null) {
            if (StringUtils.isNotBlank(baseHouseInfo.getDepType())) {
                DepModeInfo d = depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
                if (info.getOwnerState().equals(NumStrEnum.ONE.getNum()) && d.getDepType().equals(NumStrEnum.ONE.getNum())) {
                    BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.getInfoByAccNo(info.getId());
                    if (null == baseOwnerInfo.getPrice()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先维护业主的售价");
                    }
                }
            }
            BigDecimal dueAmount = calculateAmount.calculateDueAmount(baseHouseInfo);
            info.setFirstDue(dueAmount);
        }
        //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
        BaseHouseInfo houseInfo = combineEntityUtil.combineEntity(baseHouseInfo, info);
        //注意是全表更新
        int num = baseHouseInfoMapper.updateById(houseInfo);
        return CommonResult.ResponseResult(num);
    }

    @Override
    public void houseState(BaseHouseInfo baseHouseInfo) {
        if ((NumStrEnum.THREE.getNum()).equals(baseHouseInfo.getState())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在销户");
        }
        int num = flowInstanceMapper.selectChangeHouseAndOwner(baseHouseInfo.getId(), "base_house_info_update");
        if (num > 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在变更");
        }
        BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(baseHouseInfo.getId());
        if (null != baseOwnerInfo) {
            num = flowInstanceMapper.selectChangeHouseAndOwner(baseOwnerInfo.getId(), "base_owner_info_update");
            if (num > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在业主变更");
            }
            if (StringUtils.isNotBlank(baseHouseInfo.getFlowInProgress()) && !baseHouseInfo.getFlowInProgress().equals("0")) {
                switch (baseHouseInfo.getFlowInProgress()) {
                    case "deposit_develop":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "企业资金补齐");
                    case "deposit_continuation":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在续交");
                    case "ref_req":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在退款");
                    case "deposit":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在途缴存");
                    case "trans_req":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在过户");
                    case "close_account":
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "正在销户");
                }
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult delete(String idList) {
        int num = deleHouse(idList);
        return CommonResult.ResponseResult(num);
    }

    public int deleHouse(String idList) {
        int num = NumberEnum.ZERO.getNum();
        if (StringUtils.isBlank(idList)) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请选择要删除的房间！");
        }
        String[] split = idList.split(",");
        for (String id : split) {
            BaseHouseInfo n = baseHouseInfoMapper.getInfo(id);
            if (StringUtils.isNotBlank(n.getFlowInProgress()) && !("0").equals(n.getFlowInProgress())) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "有在途业务无法删除！");

            } else {
                if (expProjectReqMapper.selectHouseCount(id) > 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "有在途使用业务无法删除！");
                }
            }
            //查询有没有业主
            int count = baseOwnerInfoMapper.getCountByHouseId(id);
            if (count > 0) {
                BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.getInfoByAccNo(id);
                baseHouseInfoMapper.updateOwnerState(id, "0");
                CommonResult delete = baseOwnerInfoService.delete(baseOwnerInfo.getId());
                if (ShiroResultEnum.FAIL.getCode() == delete.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), delete.getMessage());
                }
            }
            num = baseOwnerInfoMapper.selectAllByOwner(id);
            if (num == 0) {
                //查询有没有变更
                num = baseModifyReqMapper.selectCountByBusinessId(id);
                if (num == 0) {
                    //查询有没有单元变更
                    num = baseModifyDetailMapper.selectCountByNext(id);
                    if (num == 0) {
                        num = baseHouseInfoMapper.delete(id);
                    } else {
                        num = baseHouseInfoMapper.updateState(id, "2");
                    }
                } else {
                    num = baseHouseInfoMapper.updateState(id, "2");
                }
            } else {
                num = baseHouseInfoMapper.updateState(id, "2");
            }

        }
        return num;
    }

    @Override
    public PageInfo<BaseHouseInfo> getList(Page page, BaseHouseInfo baseHouseInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getList(baseHouseInfo);
        //给是否绑定业主字段赋值
        for (BaseHouseInfo b : list) {
            if (StringUtils.isNotBlank(b.getOwnerId())) {
                b.setOwnerState(String.valueOf(NumberEnum.ONE.getNum()));
            } else {
                b.setOwnerState(String.valueOf(NumberEnum.ZERO.getNum()));
            }
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int getRoomNameCountById(String id, String roomName) {
        BaseHouseInfo info = baseHouseInfoMapper.getInfo(id);
        return baseHouseInfoMapper.getRoomNameCountBuildNoAndCellNo(info.getBuildNo(), info.getCellNo(), roomName);
    }

    @Override
    public PageInfo<BaseHouseInfo> getHouseAndOwnerList(Page page, BaseHouseInfo baseHouseInfo) {
        //赋值区域,重要
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getHouseAndOwnerList(baseHouseInfo.getBuildNo());
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 获取房屋调换页面列表
     *
     * @param page          分页信息
     * @param baseHouseInfo 查询实体
     * @return 分页实体
     */
    @Override
    public PageInfo<BaseHouseInfo> getChangeHouseList(Page page, BaseHouseInfo baseHouseInfo) {
        //赋值区域,重要
        baseHouseInfo.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getChangeHouseList(baseHouseInfo);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 获取第二层房屋调换列表
     * 根据传入的房间ID，查询当前房间所在小区的所有房间
     *
     * @param page          分页信息
     * @param baseHouseInfo 查询实体
     * @return 分页实体
     */
    @Override
    public PageInfo<BaseHouseInfo> getSecondChangeHouseList(Page page, BaseHouseInfo baseHouseInfo) {
        //查询第二层房屋
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getSecondChangeHouseList(baseHouseInfo);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 房屋调换
     *
     * @param beforeRoomId 更换前房间Id
     * @param afterRoomId  更换后房屋ID
     * @return 调换结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult change(String beforeRoomId, String afterRoomId) {
        //查看变更前房屋是否存在在途业务
        String msg = splitMergeService.checkHouseId(beforeRoomId);
        if (StringUtils.isNotBlank(msg)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "调换前房屋，" + msg);
        }
        //查看变更后房屋是否存在在途业务
        msg = splitMergeService.checkHouseId(afterRoomId);
        if (StringUtils.isNotBlank(msg)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "调换后房屋，" + msg);
        }
        // 查询变换前房屋业主信息
        ChangeBuildMsg beforeChangeBuildMsg = baseHouseInfoMapper.getChangeHouseInfo(beforeRoomId);
        // 查询变换后房屋业主信息
        ChangeBuildMsg afterChangeBuildMsg = baseHouseInfoMapper.getChangeHouseInfo(afterRoomId);
        //保存到变更表
        String uuid = UUIDUtil.getUUID();
        int num = modifyUtil.saveModifyReq(uuid, beforeRoomId, FlowTypeEnum.HOUSE_MODIFY.getType(), "", ShiroUserUtil.getUserName());
        if (num == NumberEnum.ZERO.getNum()) {
            return CommonResult.ResponseResult(num);
        }
        //保存到房屋调换详情表
        int count = modifyUtil.saveModifyHouse(beforeChangeBuildMsg, afterChangeBuildMsg, uuid);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //绑定审批流
        String initState = flowUpdateAuditUtil.initFlow(beforeRoomId, uuid, FlowTypeEnum.HOUSE_MODIFY.getType(), null);
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        if (FlowStateEnum.PASS.getState().equals(initState)) {
            //更新业务表，业主表，缴存表
            updateBusiness(beforeRoomId, afterRoomId);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 房屋调换审核
     *
     * @param id      变化ID
     * @param opinion 审批意见
     * @param mark    审批通过 audit_pass
     *                审批否决 audit_veto
     *                审批退回 audit_back
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult changeModifyAudit(String id, String opinion, String mark) {
        //查询业务id
        String businessId = baseModifyReqMapper.getBusinessId(id);
        if (StringUtils.isBlank(businessId)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
        }
        //返回审批状态
        String auditState = flowUpdateAuditUtil.audit(businessId, opinion, mark);
        if (StringUtils.isBlank(auditState)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
        }
        //终审成功，修改业务表    其他状态不做处理
        if (FlowStateEnum.PASS.getState().equals(auditState)) {
            BaseBuildModifyDetail baseBuildModifyDetail = baseBuildModifyDetailMapper.selectByPrimaryKey(id);
            //更新业务表，业主表，缴存表
            updateBusiness(baseBuildModifyDetail.getOldBusinessId(), baseBuildModifyDetail.getNewBusinessId());
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 查询房屋调换审核列表
     *
     * @param page                  分页信息
     * @param baseBuildModifyDetail 查询实体
     *                              oldAddress 房屋地址
     *                              createTime 申请开始时间
     *                              updateTime 申请结束时间
     *                              creater 申请人
     * @return 查询结果
     */
    @Override
    public PageInfo<BaseBuildModifyDetail> getChangeModifyList(Page page, BaseBuildModifyDetail baseBuildModifyDetail) {
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.HOUSE_MODIFY.getType());
        List<BaseBuildModifyDetail> list = new ArrayList<>();
        if (map != null) {
            baseBuildModifyDetail.setId(map.get("id"));
            //赋值区域,重要
            baseBuildModifyDetail.setZoneCode(map.get("zoneCode"));
            baseBuildModifyDetail.setModifyType(FlowTypeEnum.HOUSE_MODIFY.getType());
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = baseHouseInfoMapper.getChangeModifyList(baseBuildModifyDetail);
        }
        PageInfo<BaseBuildModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 查询房屋调换详情
     *
     * @param id 变更ID
     * @return 详情信息
     */
    @Override
    public BaseBuildModifyDetail getChangeDetail(String id) {
        return baseBuildModifyDetailMapper.getChangeDetail(id);
    }

    /**
     * 查询房屋调换查询列表
     *
     * @param page                  分页信息
     * @param baseBuildModifyDetail 查询实体
     *                              oldAddress 调换前房屋地址
     *                              newAddress 调换后房屋地址
     *                              createTime 申请开始时间
     *                              updateTime 申请结束时间
     *                              modifyCause 变更原因
     *                              creater 变更人
     * @return 查询结果
     */
    @Override
    public PageInfo<BaseBuildModifyDetail> getChangeModifyInfoList(Page page, BaseBuildModifyDetail baseBuildModifyDetail) {
        //赋值区域,重要
        baseBuildModifyDetail.setZoneCode(zoneCodeUtil.getZoneCode());
        baseBuildModifyDetail.setModifyType(FlowTypeEnum.HOUSE_MODIFY.getType());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseBuildModifyDetail> list = baseHouseInfoMapper.getChangeModifyInfoList(baseBuildModifyDetail);
        PageInfo<BaseBuildModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 模糊查询房屋调换变更列表
     *
     * @param page  分页实体
     * @param param 模糊查询参数
     * @return 房屋调换变更列表
     */
    @Override
    public PageInfo<BaseHouseInfo> fuzzySearch(Page page, String param) {
        //赋值区域,重要
        String zoneCode = zoneCodeUtil.getZoneCode();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.fuzzySearch(zoneCode, param);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseHouseInfo> getPageListToView(Page page, BaseHouseInfo baseHouseInfo) {
        //赋值区域,重要
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getPageListToView(baseHouseInfo);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<BaseHouseInfo> getListToView(BaseHouseInfo baseHouseInfo) {
        List<BaseHouseInfo> listToView = baseHouseInfoMapper.getListToView(baseHouseInfo);
        //过滤已缴存或处于缴存中的房屋
        Iterator<BaseHouseInfo> itr = listToView.iterator();
        while (itr.hasNext()) {
            String isDueState = depReqLogic.getIsDueState(itr.next().getId());
            if (NumStrEnum.ONE.getNum().equals(isDueState)) {
                itr.remove();
            }
        }
        for (BaseHouseInfo b : listToView) {
            DepModeInfo depModeInfo = new DepModeInfo();
            depModeInfo.setHouseId(b.getId());
            depModeInfo.setHouseType(b.getHouseAttr());
            b.setDepModeInfos(depModeInfoService.selectByAllChange(depModeInfo));
        }
        return listToView;
    }

    @Override
    public List<BaseHouseInfo> getAllListToView(BaseHouseInfo baseHouseInfo) {
        List<BaseHouseInfo> listToView = baseHouseInfoMapper.getAllListToView(baseHouseInfo);
        //过滤已缴存或处于缴存中的房屋
        for (BaseHouseInfo b : listToView) {
            int count = baseModifyReqMapper.selectCountByCellNotFlow(b.getCellId());
            b.setNum(count);
            DepModeInfo depModeInfo = new DepModeInfo();
            depModeInfo.setHouseId(b.getId());
            depModeInfo.setHouseType(b.getHouseAttr());
            b.setDepModeInfos(depModeInfoService.selectByAllChange(depModeInfo));
            String isDueState = depReqLogic.getIsDueState(b.getId());
            b.setIsDueState(NumStrEnum.ZERO.getNum());
            if (NumStrEnum.ONE.getNum().equals(isDueState)) {
                b.setIsDueState(NumStrEnum.ONE.getNum());
            }
            int num = flowInstanceMapper.selectChangeHouseAndOwner(b.getId(), "base_house_info_update");
            if (num > 0) {
                b.setIsDueState(NumStrEnum.THREE.getNum());
            }
            BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(b.getId());
            if (null != baseOwnerInfo) {
                num = flowInstanceMapper.selectChangeHouseAndOwner(baseOwnerInfo.getId(), "base_owner_info_update");
                if (num > 0) {
                    b.setIsDueState(NumStrEnum.FOUR.getNum());
                }
            }
        }
        return listToView;
    }

    @Override
    public CommonResult insertHouseByCell(BaseHouseInfo baseHouseInfo, String stepType) {
        //根据单元id、楼层号、查询房间号列表
        List<String> roomNoList = baseHouseInfoMapper.getRoomNoByCellNoAndFloorNo(baseHouseInfo.getCellNo(), baseHouseInfo.getFloorNo());
        //创建房间号
        String roomNo = null;
        if (String.valueOf(NumberEnum.ZERO.getNum()).equals(stepType)) {
            roomNo = String.valueOf(String.format("%03d", Integer.parseInt(baseHouseInfo.getRoomNo()) - 1));
        } else if (String.valueOf(NumberEnum.ONE.getNum()).equals(stepType)) {
            roomNo = String.valueOf(String.format("%03d", Integer.parseInt(baseHouseInfo.getRoomNo()) + 1));
        }
        //判断是否存在
        if (roomNoList.contains(roomNo)) {
            return CommonResult.strResult(NumberEnum.ZERO.getNum(), "房间号已存在！无法重复添加！");
        }
        //拼接坐落
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(baseHouseInfo.getBuildNo());
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(baseRegionInfo.getZoneCode(), 0, 6));
        //房屋坐落 区+小区名+自然幢名+单元名+房间名
        String houseSite = zoneName + baseRegionInfo.getRegionName() + baseBuildInfo.getBuildName();
        //房间编号
//        String sortType = baseBuildInfo.getSortType();
//        String roomName = null;
//        //String roomNo = String.format("%03d", Integer.parseInt(maxRoomNo) + 1 );
//        switch (sortType) {
//            case "0":
//                roomName = baseHouseInfo.getFloorNo() + roomNo;
//                break;
//            case "1":
//                //查询最大房间号
//                //sroomName = baseHouseInfo.getFloorNo() + String.format("%02d", houseNo );break;
//        }
        String id = UUIDUtil.getUUID();
        baseHouseInfo.setId(id);
        baseHouseInfo.setRoomNo(roomNo);
        baseHouseInfo.setHouseSite(houseSite);
        int i = baseHouseInfoMapper.insert(baseHouseInfo);
        return CommonResult.idResult(i, id);
    }

    @Override
    public CommonResult updateBatch(List<BaseHouseInfo> baseHouseInfoList) {
        int num = 0;
        for (BaseHouseInfo baseHouseInfo : baseHouseInfoList) {
            num = baseHouseInfoMapper.update(baseHouseInfo);
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<BaseHouseInfo> getBindSubHouseList(Page page, BaseHouseInfo baseHouseInfo) {
        //查询当前房屋对应的银行
        BaseHouseInfo info = baseHouseInfoMapper.getInfo(baseHouseInfo.getId());
        if (null == info || StringUtils.isBlank(info.getBankCode())) {
            return new PageInfo();
        }
        BaseOwnerInfo ownerInfo = baseOwnerInfoMapper.getInfoByAccNo(baseHouseInfo.getId());
        if (ownerInfo != null) {
            baseHouseInfo.setOwnerId(ownerInfo.getOwnerId());
        }
        baseHouseInfo.setBankCode(info.getBankCode());
        baseHouseInfo.setBuildNo(info.getBuildNo());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getBindSubHouseList(baseHouseInfo);
        //过滤处于已缴存或者缴存中的房屋
        long num = 0;
        Iterator<BaseHouseInfo> itr = list.iterator();
        while (itr.hasNext()) {
            String isDueState = depReqLogic.getIsDueState(itr.next().getId());
            if (NumStrEnum.ONE.getNum().equals(isDueState)) {
                itr.remove();
                num = num++;
            }
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<BaseHouseInfo> getOwnerListToView(Page page, BaseHouseInfo baseHouseInfo, String arcType) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getOwnerListToView(baseHouseInfo);
        //过滤处于已缴存或者缴存中的房屋
        long num = 0;
        Iterator<BaseHouseInfo> itr = list.iterator();
        while (itr.hasNext()) {
            String isDueState = depReqLogic.getIsDueState(itr.next().getAccNo());
            if (NumStrEnum.ONE.getNum().equals(isDueState)) {
                itr.remove();
                num = num++;
            }
        }

        for (BaseHouseInfo b : list) {
            if (null == b.getPrice() || b.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                b.setPrice(null);
            }
            // 查询图档信息
            List<FileVO> fileVOList = fileService.getFileVOList(b.getId(), arcType);
            b.setFileTypeList(fileVOList);
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(pageInfo.getTotal() - num);

        return pageInfo;
    }

    @Override
    public List<String> getCellNameListByBuildNo(String buildNo) {
        return baseHouseInfoMapper.getCellNameListByBuildNo(buildNo);
    }

    @Override
    public List<String> getHouseUseListByBuildNo(String buildNo) {
        return baseHouseInfoMapper.getHouseUseListByBuildNo(buildNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deleteBatchToView(String idList) {
        int num = NumberEnum.ZERO.getNum();
        if (StringUtils.isNotBlank(idList)) {
            String[] split = idList.split(",");
            for (String id : split) {
                BaseHouseInfo info = baseHouseInfoMapper.getInfo(id);
                if (expProjectReqMapper.selectHouseCount(id) > 0) {
                    return CommonResult.strResult(0, info.getHouseSite() + "有在途使用业务无法删除");
                }
                //修改房屋有无业主的状态
                baseHouseInfoMapper.updateOwnerState(info.getId(), NumStrEnum.ZERO.getNum());
                //修改房屋的价格
                baseHouseInfoMapper.updatePrice(info.getId(), null);
                BaseOwnerInfo base = baseOwnerInfoMapper.selectOwner(id);
                if (null != base) {
                    CommonResult delete = baseOwnerInfoService.delete(base.getId());
                    if (ShiroResultEnum.FAIL.getCode() == delete.getData()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), delete.getMessage());
                    }
                }
                //删除房间
                num = deleHouse(id);
            }
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult insertByFloor(String cellNo, String houseNum, String floorNo) {
        //TODO
        int num = NumberEnum.ZERO.getNum();
        //查询楼层是否存在
        int count = baseHouseInfoMapper.getCountByCellNoAndFloorNo(cellNo, floorNo);
        if (count > 0) {
            return CommonResult.strResult(NumberEnum.ZERO.getNum(), "楼层号已存在!");
        }
        //查询基础信息
        Map<String, Object> map = baseHouseInfoMapper.getMapByCellNo(cellNo);
        if (Integer.parseInt(floorNo) > (int) map.get("endFloor") || (int) map.get("startFloor") > Integer.parseInt(floorNo)) {
            return CommonResult.strResult(NumberEnum.ZERO.getNum(), "请输入正确的楼层号!");
        }
        BaseHouseInfo info = null;
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(String.valueOf(map.get("zoneCode")), 0, 4));
        for (int i = 1; i <= Integer.parseInt(houseNum); i++) {
            info = new BaseHouseInfo();
            info.setId(UUIDUtil.getUUID());
            info.setCreater(ShiroUserUtil.getUserName());
            info.setCellNo(cellNo);
            info.setBuildNo(String.valueOf(map.get("buildNo")));
            info.setHouseUse(String.valueOf(map.get("cellType")));
            info.setHouseSite(zoneName + map.get("regionName") + map.get("subRegionName") + map.get("buildName") + map.get("cellName") + floorNo + String.format("%02d", i));
            info.setRoomNo(String.format("%03d", i));
            info.setRoomName(floorNo + String.format("%02d", i));
            info.setFloorNo(floorNo);
            //info.setState(NumberEnum.ZERO.getNum());
            info.setBankCode(String.valueOf(map.get("bankCode")));
            //info.setFirstMode();
            num = baseHouseInfoMapper.insert(info);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(),"添加房屋失败");
            }
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public List<BaseHouseInfo> getCellByBuildNoAndFloorNoToInput(String floorNo, String buildNo) {
        List<BaseHouseInfo> list = baseHouseInfoMapper.getCellByBuildNoAndFloorNoToInput(floorNo, buildNo);
        for (BaseHouseInfo base : list) {
            int count = baseModifyReqMapper.selectCountByCellNotFlow(base.getId());
            base.setNum(count);
            base.setCellName(base.getCellName() + "(" + base.getDicName() + ")");
        }
        return list;
    }

    @Override
    public PageInfo<BaseHouseInfo> getHouseListToRef(Page page, BaseHouseInfo baseHouseInfo) {
        //查询出已记账的，正常状态的busi_no
        List<BaseHouseInfo> baseHouseInfolist = baseHouseInfoMapper.getHouseListToRef(baseHouseInfo);
        for (BaseHouseInfo base : baseHouseInfolist) {
            if (("1").equals(base.getDepType())) {
                BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(base.getId());
                String value = baseModifyDetailMapper.selectByReqTime(baseOwnerInfo.getId(), "price", "base_owner_info_update");
                if (StringUtils.isNotBlank(value)) {
                    base.setOldValue(value);
                } else {
                    if (null != baseOwnerInfo.getPrice()) {
                        base.setOldValue(baseOwnerInfo.getPrice().toString());
                    } else {
                        base.setOldValue("0");
                    }
                }
            } else if (("2").equals(base.getDepType()) || ("3").equals(base.getDepType())) {
                String value = baseModifyDetailMapper.selectByReqTime(base.getId(), "struArea", "base_house_info_update");
                if (StringUtils.isNotBlank(value)) {
                    base.setOldValue(value);
                } else {
                    if (null != base.getStruArea()) {
                        base.setOldValue(base.getStruArea().toString());
                    } else {
                        base.setOldValue("0");
                    }
                }
            }
            BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(base.getId());
            int num = flowInstanceMapper.selectChangeHouseAndOwner(base.getId(), "base_house_info_update");
            String isExpState = expReqLogic.getIsExpInProgress(base.getId());
            if (NumStrEnum.ONE.getNum().equals(isExpState)) {
                base.setFlowInProgress("使用在途");
                base.setNum(1);
            }
            if (num > 0) {
                base.setFlowInProgress("房屋变更");
            }
            num = flowInstanceMapper.selectChangeHouseAndOwner(baseOwnerInfo.getId(), "base_owner_info_update");
            if (num > 0) {
                base.setFlowInProgress("业主变更");
            }
            base.setNum(num);
        }
        if (baseHouseInfo.getFlowInProgress().equals(NumStrEnum.ZERO.getNum())) {
            Iterator<BaseHouseInfo> it = baseHouseInfolist.iterator();
            while (it.hasNext()) {
                BaseHouseInfo x = it.next();
                if (!x.getFlowInProgress().equals("正常")) {
                    it.remove();
                }
            }
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>();
        if (null != baseHouseInfolist && baseHouseInfolist.size() > 0) {
            pageInfo = new PageInfo<>(baseModifyDetailService.pageAll(page, baseHouseInfolist));
            pageInfo.setTotal(baseHouseInfolist.size());
        }
        return pageInfo;
    }

    @Override
    public BaseHouseInfo getHouseInfo(String houseId) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(houseId);
        baseHouseInfo.setHouseUseName(dicContentMapper.selectName(baseHouseInfo.getHouseUse()));
        baseHouseInfo.setHouseAttrName(dicContentMapper.selectName(baseHouseInfo.getHouseAttr()));
        baseHouseInfo.setFirstModeName(depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode()).getName());
        baseHouseInfo.setDepType(depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode()).getDepType());
        baseHouseInfo.setBankCodeName(baseBankInfoMapper.getInfo(baseHouseInfo.getBankCode()).getBankName());
        BigDecimal bigDecimal = BigDecimal.ZERO;
        //应交
        BigDecimal firstDue = calculateAmount.calculateDueAmount(baseHouseInfo);
        baseHouseInfo.setFirstDue(firstDue);
        //退款金额
        if (null == baseHouseInfo.getAccrBal() || baseHouseInfo.getAccrBal().equals("")) {
            if (null == baseHouseInfo.getFundBal() || baseHouseInfo.getFundBal().equals("")) {
                baseHouseInfo.setPayAmount(bigDecimal);
            }
            baseHouseInfo.setPayAmount(baseHouseInfo.getFundBal());
        } else if (null == baseHouseInfo.getFundBal() || baseHouseInfo.getFundBal().equals("")) {
            baseHouseInfo.setPayAmount(baseHouseInfo.getAccrBal());
        } else {
            baseHouseInfo.setPayAmount(baseHouseInfo.getFundBal().add(baseHouseInfo.getAccrBal()));
        }
        //账号冻结金额
        if (null != baseHouseInfo.getAccountFrozen()) {
            if (null != baseHouseInfo.getAccountFrozenBal()) {
                baseHouseInfo.setAccountFrozenAll(baseHouseInfo.getAccountFrozen().add(baseHouseInfo.getAccountFrozenBal()));
            } else {
                baseHouseInfo.setAccountFrozenAll(baseHouseInfo.getAccountFrozen());
            }
        } else {
            baseHouseInfo.setAccountFrozenAll(baseHouseInfo.getAccountFrozenBal());
        }
        if (StringUtils.isNotBlank(baseHouseInfo.getDueState())) {
            if (baseHouseInfo.getDueState().equals(NumStrEnum.TWO.getNum()) || baseHouseInfo.getDueState().equals(NumStrEnum.ONE.getNum()) || baseHouseInfo.getDueState().equals(NumStrEnum.FIVE.getNum())) {
                baseHouseInfo.setDueState("是");
            } else {
                baseHouseInfo.setDueState("否");
            }
        }
        //todo 销户利息
        return baseHouseInfo;
    }

    @Override
    public PageInfo<BaseHouseInfo> getListToRef(Page page, String bulidNo, String refType) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getListToRef(bulidNo);
        //申请类型 225销户 226部分返还 227全额返还
        list.forEach(l -> {
            if (null == l.getPayAmount() || l.getPayAmount().compareTo(BigDecimal.ZERO) == 0) {
                l.setPayAmount(refReqServiceImpl.getMaxPayAmount(l, refType));
            }
            l.setMaxRefAmount(l.getPayAmount());
            if ("225".equals(refType) || "227".equals(refType)) {
                BigDecimal payAccrCal = refReqServiceImpl.getPayAccrCal(refType, l.getId());
                log.info("计算截止当前利息为:" + payAccrCal);
                if (null == l.getAccrBal() || l.getAccrBal().compareTo(BigDecimal.ZERO) == 0) {
                    l.setAccrBal(BigDecimal.ZERO);
                }
                l.setAccrBal(l.getAccrBal().add(payAccrCal));
                //使用在途:不影响部分退款,不可全额退款、销户
                if (NumStrEnum.ZERO.getNum().equals(l.getFlowInProgress())) {
                    String isExpState = expReqLogic.getIsExpInProgress(l.getId());
                    if (NumStrEnum.ONE.getNum().equals(isExpState)) {
                        l.setFlowInProgress("project_req");
                        l.setProgressName("使用在途");
                    }
                }
            }
            //交存在途:不可全额退款、部分退款、销户
            if (NumStrEnum.ZERO.getNum().equals(l.getFlowInProgress())) {
                BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.getInfoByAccNo(l.getId());
                int count = baseHouseInfoMapper.getCountDepReqListByHouseId(l.getId(), baseOwnerInfo.getId());
                if (count > 0) {
                    l.setFlowInProgress("deposit");
                    l.setProgressName("交存在途");
                }
            }
        });
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据小区ID查询房间列表
     *
     * @param regionId 小区ID
     * @param buildId  自然幢ID
     * @param cellId   单元ID
     * @return 房间列表
     */
    @Override
    public List<BaseHouseInfo> getHouseListByRegionId(String regionId, String buildId, String cellId) {
        return baseHouseInfoMapper.getHouseListByRegionId(regionId, buildId, cellId);
    }

    @Override
    public PageInfo<BaseModifyDetail> getModifyDetailList(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseModifyDetail> list = baseHouseInfoMapper.getModifyDetailList(id);
        for (BaseModifyDetail modifyDetail : list) {
            switch (modifyDetail.getColumnName()) {
                case "firstMode":
                    String newFirstMode = depModeInfoMapper.getInfo(modifyDetail.getNewValue()).getName();
                    String oldFirstMode = depModeInfoMapper.getInfo(modifyDetail.getOldValue()).getName();

                    modifyDetail.setNewValue(null == newFirstMode ? "" : newFirstMode);
                    modifyDetail.setOldValue(null == oldFirstMode ? "" : oldFirstMode);
                    break;
                case "houseAttr":
                    String newHouseAttr = dicContentMapper.selectName(modifyDetail.getNewValue());
                    String oldHouseAttr = dicContentMapper.selectName(modifyDetail.getOldValue());
                    modifyDetail.setNewValue(null == newHouseAttr ? "" : newHouseAttr);
                    modifyDetail.setOldValue(null == oldHouseAttr ? "" : oldHouseAttr);
                    break;
                case "dueState":
                    String newDueState = modifyDetail.getNewValue();
                    String oldDueState = modifyDetail.getOldValue();
                    if (StringUtils.isBlank(newDueState)) {
                        modifyDetail.setNewValue("");
                    } else {
                        if (newDueState.equals(NumStrEnum.ONE.getNum())) {
                            modifyDetail.setNewValue("足额");
                        } else if (newDueState.equals(NumStrEnum.TWO.getNum())) {
                            modifyDetail.setNewValue("多额");
                        } else if (newDueState.equals(NumStrEnum.THREE.getNum())) {
                            modifyDetail.setNewValue("少额");
                        } else if (newDueState.equals(NumStrEnum.FOUR.getNum())) {
                            modifyDetail.setNewValue("未交");
                        }
                    }
                    if (StringUtils.isBlank(oldDueState)) {
                        modifyDetail.setOldValue("");
                    } else {
                        if (oldDueState.equals(NumStrEnum.ONE.getNum())) {
                            modifyDetail.setOldValue("足额");
                        } else if (oldDueState.equals(NumStrEnum.TWO.getNum())) {
                            modifyDetail.setOldValue("多额");
                        } else if (oldDueState.equals(NumStrEnum.THREE.getNum())) {
                            modifyDetail.setOldValue("少额");
                        } else if (oldDueState.equals(NumStrEnum.FOUR.getNum())) {
                            modifyDetail.setOldValue("未交");
                        }
                    }
                    break;
            }
        }
        PageInfo<BaseModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 房屋结构变更
     *
     * @param baseHouseInfos
     * @return
     */
    @Override
    public CommonResult updateToSaveByHouse(List<BaseHouseInfo> baseHouseInfos) throws Exception {
        String cellNo = baseHouseInfos.get(0).getCellNo();
        baseHouseInfos.remove(0);
        for (BaseHouseInfo b : baseHouseInfos) {
            int no = baseModifyDetailMapper.selectHouseChange(b.getCellNo());
            if (no > 0) {
                int i = baseModifyDetailMapper.deleteByCell(b.getCellNo());
                if (i == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "删除原数据操作失败");

                }
            }
        }
        //获取新id
        List<String> newId = new ArrayList<>();
        for (BaseHouseInfo b : baseHouseInfos) {
            //看业主是否维护价格
            ownerPrice(b);
            newId.add(b.getId());
        }
        //获取旧id
        List<String> oldId = new ArrayList<>();
        List<BaseHouseInfo> oldList = baseHouseInfoMapper.selectByCellNo(cellNo);
        for (BaseHouseInfo b : oldList) {
            oldId.add(b.getId());
        }
        //查看有相同的id
        for (int i = 0; i < baseHouseInfos.size(); i++) {
            BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
            if (StringUtils.isNotBlank(newId.get(i))) {
                baseHouseInfo = baseHouseInfoMapper.getInfo(newId.get(i));
                baseHouseInfo.setHouseUseName(baseHouseInfos.get(i).getHouseUseName());
                baseHouseInfo.setFirstDue(baseHouseInfos.get(i).getFirstDue());
                baseHouseInfo.setAccrBal(baseHouseInfos.get(i).getAccrBal());
                baseHouseInfo.setAccountFrozen(baseHouseInfos.get(i).getAccountFrozen());
                baseHouseInfo.setHouseCity(baseHouseInfos.get(i).getHouseCity());
                baseHouseInfo.setPrice(baseHouseInfos.get(i).getPrice());
                baseHouseInfo.setFundBal(baseHouseInfos.get(i).getFundBal());
                baseHouseInfo.setSubRegionName(baseHouseInfos.get(i).getSubRegionName());
                baseHouseInfo.setDepModeInfos(baseHouseInfos.get(i).getDepModeInfos());
                baseHouseInfo.setZoneName(baseHouseInfos.get(i).getZoneName());
                baseHouseInfo.setBuildName(baseHouseInfos.get(i).getBuildName());
                baseHouseInfo.setCellName(baseHouseInfos.get(i).getCellName());
                baseHouseInfo.setRegionName(baseHouseInfos.get(i).getRegionName());
            }
            BigDecimal str = null;
            BigDecimal f = baseHouseInfos.get(i).getStruArea();
            if (null != baseHouseInfos.get(i).getStruArea()) {
                DecimalFormat df3 = new DecimalFormat("0.00");
                str = new BigDecimal(df3.format(f));
            }
            baseHouseInfos.get(i).setStruArea(str);
            //若相同查询变更项
            if (oldId.contains(baseHouseInfos.get(i).getId())) {
                baseHouseInfo.setRegionName(baseHouseInfos.get(i).getRegionName());
                baseHouseInfo.setBuildName(baseHouseInfos.get(i).getBuildName());
                baseHouseInfo.setCellName(baseHouseInfos.get(i).getCellName());
                modifyUtil.saveModifyDetailCell(baseHouseInfo, baseHouseInfos.get(i), baseHouseInfo.getId(), baseHouseInfo.getCellNo());
                Iterator<String> itr = oldId.iterator();
                while (itr.hasNext()) {
                    if (itr.next().contains(newId.get(i))) {
                        itr.remove();
                    }
                }
            }//若id为空则为添加数据
            if (StringUtils.isBlank(baseHouseInfos.get(i).getId())) {
                String uuid = UUIDUtil.getUUID();
                BaseModifyDetail baseModifyDetail = new BaseModifyDetail();
                baseModifyDetail.setBusinessId(baseHouseInfos.get(i).getCellNo());
                baseModifyDetail.setBusinessNextId(uuid);
                baseModifyDetail.setNewValue(uuid);
                baseModifyDetail.setColumnName("id");
                baseModifyDetail.setId(UUIDUtil.getUUID());
                baseModifyDetail.setType(NumStrEnum.ONE.getNum());
                baseModifyDetail.setName("房屋id");
                baseModifyDetail.setCreater(ShiroUserUtil.getUserName());
                baseModifyDetailMapper.insert(baseModifyDetail);
                modifyUtil.saveModifyDetailCell(new BaseHouseInfo(), baseHouseInfos.get(i), uuid, baseHouseInfos.get(i).getCellNo());
            }
        }//删除
        if (oldId.size() > 0) {
            for (String oldIds : oldId) {
                BaseHouseInfo b = baseHouseInfoMapper.getInfo(oldIds);
                BaseModifyDetail baseModifyDetail = new BaseModifyDetail();
                baseModifyDetail.setBusinessId(b.getCellNo());
                baseModifyDetail.setBusinessNextId(b.getId());
                baseModifyDetail.setOldValue(b.getId());
                baseModifyDetail.setId(UUIDUtil.getUUID());
                baseModifyDetail.setColumnName("id");
                baseModifyDetail.setType(NumStrEnum.ONE.getNum());
                baseModifyDetail.setCreater(ShiroUserUtil.getUserName());
                BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
                baseHouseInfo.setHouseSite("");
                baseHouseInfo.setHouseAttr("");
                baseHouseInfo.setHouseUse("");
                baseHouseInfo.setFirstMode("");
                baseHouseInfo.setRoomName("");
                baseHouseInfo.setStruArea(BigDecimal.ZERO);
                baseHouseInfo.setCellNo("");
                baseHouseInfo.setBuildNo("");
                baseHouseInfo.setRoomNo("");
                baseHouseInfo.setFloorNo("");
                baseHouseInfo.setId(oldIds);
                baseModifyDetailMapper.insert(baseModifyDetail);
                modifyUtil.saveModifyDetailCell(b, baseHouseInfo, b.getId(), b.getCellNo());
            }
        }
        return CommonResult.ResponseResult(1);
    }

    private void ownerPrice(BaseHouseInfo b) {
        if (StringUtils.isNotBlank(b.getFirstMode())) {
            DepModeInfo d = depModeInfoMapper.getInfo(b.getFirstMode());
            if (d.getDepType().equals(NumStrEnum.ONE.getNum())) {
                BaseOwnerInfo base = baseOwnerInfoMapper.getInfoByAccNo(b.getId());
                if (null != base) {
                    if (null == base.getPrice() && base.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先去业主变更维护" + b.getRoomName() + "的售价");
                    }
                }
            }
        }
    }

    /**
     * 房屋结构变更审核
     *
     * @param id
     * @param opinion
     * @param mark
     * @return
     */
    @Override
    @Transactional
    public CommonResult modifyAuditHouse(String id, String buildId, String opinion, String mark) {
        //查询变更的单元id
        List<String> cellIds = baseModifyDetailMapper.selectByReqNoIdCell(id);
        BaseCellInfo base = baseCellInfoMapper.getInfoById(cellIds.get(0));
        //list转String
        String cellId = String.join(",", cellIds);
        String auditState = flowUpdateAuditUtil.audit(base.getBuildNo(), opinion, mark);
        int num = NumberEnum.ZERO.getNum();
        //终审
        if (null != auditState) {
            num = NumberEnum.ONE.getNum();
            //终审成功，修改业务表    其他状态不做处理
            if (FlowStateEnum.PASS.getState().equals(auditState)) {
                baseModifyReqServiceImpl.changeHouse(id, buildId, cellId);
            }
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public List<BaseHouseInfo> selectAllHouseAndChange(String reqNo, String cellId) {
        List<BaseHouseInfo> baseHouseInfos = baseHouseInfoMapper.selectByCellNoList(cellId);
        for (BaseHouseInfo b : baseHouseInfos) {
            int num = flowInstanceMapper.getCountByBusinessIdByType(b.getId(), "base_house_info_update");
            b.setNum(num);
        }
        List<String> list = baseModifyDetailMapper.getColumnListNull();
        int change = baseModifyDetailMapper.selectHaveChange(cellId);
        Map map = new HashMap();
        map.put("list", list);
        if (change != 0) {
            List<String> changeHouseId = baseModifyDetailMapper.reqNoChangeHouse(null);
            List<String> changeHouseInfo = baseModifyDetailMapper.selectBusinessNextByReqNoId(null);
            if (changeHouseInfo.size() != 0) {
                for (String chang : changeHouseInfo) {
                    changeHouseId.add(chang);
                }
            }
            for (String id : changeHouseId) {
                int changeHouse = baseModifyDetailMapper.selectChangeHouseById(id, id);
                if (changeHouse == 0) {//修改
                    BaseHouseInfo ba = baseHouseInfoMapper.getInfo(id);
                    if (null != ba) {
                        BaseHouseInfo baseHouseInfo = modifyUtil.getNewCompleteEntityList(id, ba, reqNo);
                        Iterator<BaseHouseInfo> iterator = baseHouseInfos.iterator();
                        while (iterator.hasNext()) {
                            BaseHouseInfo baseh = iterator.next();
                            if (ba.getId().equals(baseh.getId())) {
                                iterator.remove();
                            }
                        }
                        baseHouseInfos.add(baseHouseInfo);
                    }
                }
            }
            //zengjia
            List<String> ids = baseModifyDetailMapper.selectByReqNoTypeNull(null);
            if (ids.size() != 0) {
                for (String id : ids) {
                    Map maps = new HashMap();
                    maps.put("list", list);
                    maps.put("id", id);
                    BaseHouseInfo base = baseModifyDetailMapper.selectHouseAllListNotReq(maps);
                    baseHouseInfos.add(base);
                }
            }

            //shanchu
            List<String> delIds = baseModifyDetailMapper.selectByReqNoTypeNullDel(null);
            //遍历删除
            if (delIds.size() != 0) {
                Iterator<BaseHouseInfo> iterator = baseHouseInfos.iterator();
                while (iterator.hasNext()) {
                    BaseHouseInfo baseHouseInfo = iterator.next();
                    for (String s : delIds) {
                        if (s.equals(baseHouseInfo.getId())) {
                            iterator.remove();//使用迭代器的删除方法删除
                        }
                    }
                }
            }
        }
        String buildName = "";
        String regionName = "";
        String subRegionName = "";
        String zoneNmae = "";
        if (!baseHouseInfos.isEmpty()) {
            BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(baseHouseInfos.get(0).getBuildNo());
            buildName = baseBuildInfo.getBuildName();
            regionName = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo()).getRegionName();
            if (StringUtils.isNotBlank(baseBuildInfo.getSubRegionNo())) {
                subRegionName = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo()).getSubRegionName();
                zoneNmae = zoneCodeMapper.selectNameById(baseBuildInfo.getZoneCode().substring(0, 4));
            }
        }
        for (BaseHouseInfo b : baseHouseInfos) {
            b.setHouseCity(baseHouseInfoMapper.getHouseCityById(b.getId()));
            b.setHouseUseName(dicContentMapper.selectName(b.getHouseUse()));
            b.setCellName(baseCellInfoMapper.getInfo(b.getCellNo()).getCellName());
            b.setSubRegionName(subRegionName);
            b.setBuildName(buildName);
            b.setRegionName(regionName);
            b.setBuildName(buildName);
            b.setZoneName(zoneNmae);
            DepModeInfo depModeInfo = new DepModeInfo();
            depModeInfo.setHouseId(b.getId());
            depModeInfo.setHouseType(b.getHouseAttr());
            b.setDepModeInfos(depModeInfoService.selectByAllChange(depModeInfo));
        }
        Collections.sort(baseHouseInfos);
        return baseHouseInfos;
    }

    @Override
    public CommonResult delHouseAndOwner(String idList) {
        int num = 0;
        if (StringUtils.isBlank(idList)) {
            return CommonResult.strResult(num, "请选择要删除的房间！");
        }
        String[] split = idList.split(",");
        for (String id : split) {
            //检查在途业务
            int count = baseOwnerInfoMapper.getCountByHouseId(id);
            if (count > 0) {
                num = baseOwnerInfoMapper.deleteByAccNo(id);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改Log表错误");
                }
            }
            num = baseHouseInfoMapper.delete(id);
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public PageInfo<BaseHouseInfo> houseAndOwner(Page page, BaseHouseInfo baseHouseInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> baseHouseInfos = baseHouseInfoMapper.houseAndOwner(baseHouseInfo);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(baseHouseInfos);

        return pageInfo;
    }

    @Override
    public BaseHouseInfo selectHouseById(String id) {
        return baseHouseInfoMapper.selectHouseById(id);
    }

    @Override
    public BaseHouseInfo selectCountByBuildId(String buildNo) {
        return baseHouseInfoMapper.selectCountByBuildId(buildNo);
    }

    @Override
    public BaseHouseInfo selectCountByRegionNo(String regionNo) {
        return baseHouseInfoMapper.selectCountByRegionNo(regionNo);
    }

    @Override
    public PageInfo<BaseHouseInfo> selectBydepReqList(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> baseHouseInfos = baseHouseInfoMapper.selectBydepReqList(id);
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(baseHouseInfos);

        return pageInfo;
    }

    private BigDecimal getPayAmount(BaseHouseInfo baseHouseInfo, String refType) {
        //TODO 退款金额计算方式（未做记账模块）
        BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(baseHouseInfo.getId());
        BigDecimal payAmount = null;
        switch (refType) {
            //申请类型 225销户 226部分返还 227全额返还  226需记账模块暂时不做操作
            case "225":
                RefReq refReq = refReqMapper.selectRefReqByHouseId(baseHouseInfo.getId());
                LocalDate beginDateTime = LocalDate.parse(DateUtils.getDateNow(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                //查询交存
                LocalDate tateDate;
                if (com.softer.wxzj.common.util.StringUtils.isBlank(baseHouseInfo.getRateDate())) {
                    AccTransactionLog accTransactionLog = accTransactionLogMapper.selectOldDep(baseHouseInfo.getId());
                    tateDate = LocalDate.parse(accTransactionLog.getTallyDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                } else {
                    tateDate = LocalDate.parse(baseHouseInfo.getRateDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                }
                String paramName = "销户利率";
                BigDecimal accr = selectAccr(beginDateTime, tateDate, paramName);
                payAmount = baseHouseInfo.getFundBal().add(baseHouseInfo.getAccrBal()).add(accr);
                break;
            case "226":
                payAmount = getPartPayAmount(baseHouseInfo);
                break;
            case "227":
                payAmount = baseHouseInfo.getFundBal().add(baseHouseInfo.getAccrBal());
                break;
        }
        return payAmount;
    }

    /**
     * 部分退款金额计算
     *
     * @param baseHouseInfo
     * @return
     */
    private BigDecimal getPartPayAmount(BaseHouseInfo baseHouseInfo) {
        BigDecimal payAmount;
        //缴存已记账金额汇总
        BigDecimal depMoney = depReqListInfoMapper.getMoney(baseHouseInfo.getId());
        //退款已记账金额汇总
        BigDecimal refMoney = refReqListMapper.getMoney(baseHouseInfo.getId());
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal firstDue = baseHouseInfo.getFirstDue() != null ? baseHouseInfo.getFirstDue() : BigDecimal.ZERO;
        payAmount = depMoney.subtract(refMoney).subtract(firstDue);
        int r = payAmount.compareTo(BigDecimal.ONE);
        if (r == -1) {
            return zero;
        }
        return payAmount;
    }

    BigDecimal selectAccr(LocalDate beginDateTime, LocalDate startDateTime, String paramName) {
        int days = (int) ChronoUnit.DAYS.between(beginDateTime, startDateTime);
        BigDecimal day = new BigDecimal(days);
        String value = sysCoreParamMapper.selectOne(paramName);
        BigDecimal bigDecimal = new BigDecimal(value);
        BigDecimal accr = bigDecimal.subtract(day);
        return accr;
    }


    /**
     * 更新房屋表，业主表，缴存表
     *
     * @param beforeRoomId 调换前房间ID
     * @param afterRoomId  调换后房间ID
     */
    private void updateBusiness(String beforeRoomId, String afterRoomId) {
        //修改房屋表
        updateRoom(beforeRoomId, afterRoomId);
        //修改业主表
        updateOwner(beforeRoomId, afterRoomId);
        //修改交存表
        updateDepReqList(beforeRoomId, afterRoomId);
        //修改退款表
        updateRefReqList(beforeRoomId, afterRoomId);
        //修改log表
        updateTransactionLog(beforeRoomId, afterRoomId);
        //TODO 待定需要更新的其他表
    }

    /**
     * 修改log表
     *
     * @param beforeRoomId 调换前房屋ID
     * @param afterRoomId  调换后房屋id
     */
    private void updateTransactionLog(String beforeRoomId, String afterRoomId) {
        //查询 调换前 房屋log表集合
        List<AccTransactionLog> beforeTransactionLog = baseHouseInfoMapper.getTransactionLog(beforeRoomId);
        //查询 调换后 房屋log表集合
        List<AccTransactionLog> afterTransactionLog = baseHouseInfoMapper.getTransactionLog(afterRoomId);
        dealTransactionLog(beforeTransactionLog, afterRoomId);
        dealTransactionLog(afterTransactionLog, beforeRoomId);
    }

    /**
     * 修改log表
     *
     * @param transactionLog 需要修改的log表集合
     * @param houseId        房间ID
     */
    private void dealTransactionLog(List<AccTransactionLog> transactionLog, String houseId) {
        if (transactionLog != null && !transactionLog.isEmpty()) {
            transactionLog.forEach(x -> {
                int num = baseHouseInfoMapper.updateTransactionLog(houseId, x.getId());
                if (num != 1) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改Log表错误");
                }
            });
        }
    }

    /**
     * 修改退款表
     *
     * @param beforeRoomId 调换前房屋ID
     * @param afterRoomId  调换后房屋id
     */
    private void updateRefReqList(String beforeRoomId, String afterRoomId) {
        //查询调换前退款集合
        List<RefReqList> beforeRefList = baseHouseInfoMapper.getRefList(beforeRoomId);
        //查询调换后退款集合
        List<RefReqList> afterRefList = baseHouseInfoMapper.getRefList(afterRoomId);
        dealRefList(beforeRefList, afterRoomId);
        dealRefList(afterRefList, beforeRoomId);
    }

    /**
     * 处理退款表
     *
     * @param refList 退款集合
     * @param houseId 退款房间
     */
    private void dealRefList(List<RefReqList> refList, String houseId) {
        if (refList != null && !refList.isEmpty()) {
            refList.forEach(x -> {
                int num = baseHouseInfoMapper.updateRefReqList(houseId, x.getId());
                if (num != 1) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改退款表错误");
                }
            });
        }
    }

    /**
     * 修改交存表
     *
     * @param beforeRoomId 调换前房屋ID
     * @param afterRoomId  调换后房屋id
     */
    private void updateDepReqList(String beforeRoomId, String afterRoomId) {
        //查询调换前房屋交存集合
        List<DepReqListInfo> beforeDepList = baseHouseInfoMapper.getDepList(beforeRoomId);
        //查询调换后房屋交存集合
        List<DepReqListInfo> afterDepList = baseHouseInfoMapper.getDepList(afterRoomId);
        dealDepList(beforeDepList, afterRoomId);
        dealDepList(afterDepList, beforeRoomId);
    }

    /**
     * 修改交存表
     *
     * @param depList 交存列表
     * @param houseId 修改的房间ID
     */
    private void dealDepList(List<DepReqListInfo> depList, String houseId) {
        //查询房间信息
        BaseHouseInfo houseInfo = baseHouseInfoMapper.getInfo(houseId);
        if (depList != null && depList.size() > 0) {
            depList.forEach(x -> {
                int num = baseHouseInfoMapper.updateDepHouseId(houseId, x.getId(), houseInfo.getBuildNo());
                if (num != 1) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改交存表错误");
                }
            });
        }
    }

    /**
     * 房屋变更审核
     *
     * @param id      不是业务id
     * @param opinion 意见
     * @param mark    同意/拒绝
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult changeResidentialCommittee(String id, String opinion, String mark) {
        String bId = baseModifyReqMapper.getBusinessId(id);
        String auditState = flowUpdateAuditUtil.audit(bId, opinion, mark);
        BaseModifyReq baseModifyReq = new BaseModifyReq();
        baseModifyReq.setId(id);
        baseModifyReq.setModifyCause(opinion);
        int num = NumberEnum.ZERO.getNum();
        //终审
        if (null != auditState) {
            num = NumberEnum.ONE.getNum();
            //终审成功，修改业务表    其他状态不做处理
            if (FlowStateEnum.PASS.getState().equals(auditState)) {
                //查询数据库原数据
                BaseHouseInfo info = baseHouseInfoMapper.getInfo(bId);
                BaseHouseInfo oldHouse = new BaseHouseInfo();
                //修改房屋
                //info.setHouseSite(changHouse(info));
                oldHouse.setName(info.getRoomName());
                //变更值合并到原数据
                BaseHouseInfo completeEntity = modifyUtil.getCompleteEntity(id, info);
                num = baseHouseInfoMapper.updateById(baseOwnerInfoService.changeFirst(completeEntity));
            }
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public CommonResult insertOrUpdate(List<BaseHouseInfo> baseHouseInfoList) {
        if (null == baseHouseInfoList || baseHouseInfoList.size() == 0) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "请选择至少一条数据");
        }
        int num = NumberEnum.ZERO.getNum();
        //拼接坐落
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(baseHouseInfoList.get(0).getBuildNo());
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(baseRegionInfo.getZoneCode(), 0, 4));
        for (BaseHouseInfo baseHouseInfo : baseHouseInfoList) {
            if (StringUtils.isNotBlank(baseHouseInfo.getId())) {
                BaseHouseInfo b = baseHouseInfoMapper.getInfo(baseHouseInfo.getId());
                if (!b.getFlowInProgress().equals(NumStrEnum.ZERO.getNum()) && null != b.getFlowInProgress()) {
                    System.out.println("_________________" + b.getHouseSite());
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "有在途业务，不允许操作！");
                }
                if (!b.getDueState().equals(NumStrEnum.FOUR.getNum()) && null != b.getDueState() && !b.getState().equals("0")) {
                    System.out.println("_________________" + b.getHouseSite());
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "房屋已经缴存，不允许操作，请走业主变更！");
                }
                if (StringUtils.isBlank(baseHouseInfo.getId())) {
                    baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
                }
                dealFirstMode(baseHouseInfo);
                if (StringUtils.isBlank(baseHouseInfo.getFirstMode()) && StringUtils.isBlank(baseHouseInfo.getHouseAttr()) && (null == baseHouseInfo.getStruArea() || baseHouseInfo.getStruArea().compareTo(BigDecimal.ZERO) == 0)) {
                    if (baseHouseInfo.getOwnerState().equals(NumStrEnum.ONE.getNum())) {
                        return new CommonResult(ShiroResultEnum.FAIL.getCode(), "有业主无法清空房屋信息");
                    }
                    num = baseHouseInfoMapper.updateView(baseHouseInfo);
                } else {
                    num = baseHouseInfoMapper.update(baseHouseInfo);
                }
            } else {
                baseHouseInfo.setCreater(ShiroUserUtil.getUserName());
                if (StringUtils.isBlank(baseHouseInfo.getId())) {
                    baseHouseInfo.setId(UUIDUtil.getUUID());
                    baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
                }
                dealFirstMode(baseHouseInfo);
                BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(baseHouseInfo.getCellNo());
                //房屋坐落 区+小区名+自然幢名+单元名
                if (StringUtils.isBlank(baseBuildInfo.getSubRegionName())) {
                    baseBuildInfo.setSubRegionName("");
                }
                if (StringUtils.isBlank(baseHouseInfo.getHouseSite())) {
                    String houseSite = zoneName + baseRegionInfo.getRegionName() + baseBuildInfo.getSubRegionName() + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + baseHouseInfo.getRoomName();
                    baseHouseInfo.setHouseSite(houseSite);
                }
                baseHouseInfo.setBankCode(baseBuildInfo.getBankCode());
                num = baseHouseInfoMapper.insert(baseHouseInfo);
            }
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 处理交存模式
     *
     * @param baseHouseInfo 房屋基本信息
     */
    private void dealFirstMode(BaseHouseInfo baseHouseInfo) {
        String firstMode = baseHouseInfo.getFirstMode();
        if (StringUtils.isNotBlank(firstMode)) {
            DepModeInfo depModeInfo = depModeInfoMapper.getInfo(firstMode);
            if (!String.valueOf(NumberEnum.ONE.getNum()).equals(depModeInfo.getDepType())) {
                baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
            }
        }
    }

    @Override
    public List<BaseHouseInfo> getAllList(BaseHouseInfo baseHouseInfo) {
        int count;
        List<BaseHouseInfo> list;
        if (baseHouseInfo.getNum() == 1) {
            list = baseHouseInfoMapper.selectHaveDep(baseHouseInfo);
            //给是否绑定业主字段赋值
            for (BaseHouseInfo b : list) {
                count = flowInstanceMapper.getCountByBusinessId(b.getId());
                if (count != 0) {
                    //0不可以变更
                    b.setChange(String.valueOf(NumberEnum.ZERO.getNum()));
                    b.setMsg("该房屋正在变更不可以变更");
                } else {
                    if (null != b.getFlowInProgress() && !b.getFlowInProgress().equals(NumStrEnum.ZERO.getNum())) {
                        switch (b.getFlowInProgress()) {
                            case "trans_req":
                                b.setMsg("该房屋正在过户不可以变更");
                                break;
                            case "deposit":
                                b.setMsg("该房屋正在交存不可以变更");
                                break;
                            case "ref_req":
                                b.setMsg("该房屋正在退款不可以变更");
                                break;
                        }
                        b.setChange(String.valueOf(NumberEnum.ZERO.getNum()));
                    } else if (null != b.getAccountFrozen() && b.getAccountFrozen().compareTo(new BigDecimal(0.00)) != 0) {
                        b.setChange(String.valueOf(NumberEnum.ZERO.getNum()));
                        b.setMsg("该房屋正在使用不可以变更");
                    } else {
                        //1可以变更
                        b.setChange(String.valueOf(NumberEnum.ONE.getNum()));
                    }
                }
            }
        } else {
            list = baseHouseInfoMapper.selectNotDep(baseHouseInfo);
            if (!list.isEmpty()) {
                for (BaseHouseInfo b : list) {
                    ownerPrice(b);
                    b.setChange(NumStrEnum.ONE.getNum());
                }
            }
            //过滤已缴存或处于缴存中的房屋
            Iterator<BaseHouseInfo> itr = list.iterator();
            while (itr.hasNext()) {
                String isDueState = depReqLogic.getIsDueState(itr.next().getId());
                if (NumStrEnum.ONE.getNum().equals(isDueState)) {
                    itr.remove();
                }
            }
        }
        //拼接houseCity
        list.forEach(l -> {
            String houseCity = baseHouseInfoMapper.getHouseCityById(l.getId());
            BaseHouseInfo baseHouseInfoName = baseHouseInfoMapper.getHouseAllName(l.getId());
            l.setHouseCity(houseCity);
            l.setBuildName(baseHouseInfoName.getBuildName());
            l.setCellName(baseHouseInfoName.getCellName());
            l.setRegionName(baseHouseInfoName.getRegionName());
            l.setSubRegionName(baseHouseInfoName.getSubRegionName());
            l.setZoneName(baseHouseInfoName.getZoneName());
            DepModeInfo depModeInfo = new DepModeInfo();
            depModeInfo.setHouseId(l.getId());
            depModeInfo.setHouseType(l.getHouseAttr());
            l.setDepModeInfos(depModeInfoService.selectByAllChange(depModeInfo));
        });
        if (baseHouseInfo.getNum() == 2) {
            list.forEach(l -> {
                l.setFirstMode(null);
            });
        }
        return list;
    }

    @Override
    public PageInfo<BaseHouseInfo> getListNotDep(Page page, BaseHouseInfo baseHouseInfo) {
        //赋值区域,重要
        //baseHouseInfo.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getListNotDep(baseHouseInfo);
        //给是否绑定业主字段赋值
        for (int i = 0; i < list.size(); i++) {
            if (StringUtils.isNotBlank(list.get(i).getOwnerId())) {
                int num = depReqListInfoMapper.selectCountHouse(list.get(i).getId());
                if (num > 0) {
                    list.get(i).setOwnerState(String.valueOf(NumberEnum.ONE.getNum()));
                    list.get(i).setMsg("正在交存无法修改业主信息");
                }
                list.get(i).setOwnerState(String.valueOf(NumberEnum.ONE.getNum()));
            } else {
                list.get(i).setOwnerState(String.valueOf(NumberEnum.ZERO.getNum()));
            }
        }
        PageInfo<BaseHouseInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 修改业主表
     * 将业主表中的房间Id调换
     *
     * @param beforeRoomId 调换前房间ID
     * @param afterRoomId  调换后房间ID
     */
    private void updateOwner(String beforeRoomId, String afterRoomId) {
        //查询调换前业主和共有人
        List<BaseOwnerInfo> beforeList = baseOwnerInfoMapper.getBaseOwnerInfoByAccNo(beforeRoomId);
        //查询调换后业主和共有人
        List<BaseOwnerInfo> afterList = baseOwnerInfoMapper.getBaseOwnerInfoByAccNo(afterRoomId);
        //将变化后房屋ID更新到调换前业主中
        dealOwnerInfo(beforeList, afterRoomId);
        //将调换前房屋ID更新到调换后的业主中
        dealOwnerInfo(afterList, beforeRoomId);
    }

    /**
     * 修改业主信息
     *
     * @param list 业主和共有人集合
     * @param id   房间ID
     */
    private void dealOwnerInfo(List<BaseOwnerInfo> list, String id) {
        if (list != null && list.size() > NumberEnum.ZERO.getNum()) {
            for (BaseOwnerInfo baseOwnerInfo : list) {
                baseOwnerInfo.setAccNo(id);
                int num = baseOwnerInfoMapper.update(baseOwnerInfo);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
    }

    /**
     * 修改房屋表
     * 房屋表中，修改余额，银行编码，利息，计息日期，结息类型，在用利率，账户状态，购房日期
     *
     * @param beforeRoomId 调换前房间ID
     * @param afterRoomId  调换后房间ID
     */
    private void updateRoom(String beforeRoomId, String afterRoomId) {
        //查询调换前房间信息
        BaseHouseInfo beforeInfo = baseHouseInfoMapper.getInfo(beforeRoomId);
        //查询调换后房屋信息
        BaseHouseInfo afterInfo = baseHouseInfoMapper.getInfo(afterRoomId);

        //设置交存状态
        setDueState(beforeInfo, afterInfo, beforeRoomId, afterRoomId);
        //需要修改的字段
        setRoomParam(beforeInfo, afterInfo);
        //修改房间表
        int num = baseHouseInfoMapper.update(beforeInfo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        int count = baseHouseInfoMapper.update(afterInfo);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 设置交存状态
     *
     * @param beforeInfo   调换前房屋信息
     * @param afterInfo    调换后房屋信息
     * @param beforeRoomId 调换前房屋ID
     * @param afterRoomId  调换后房屋ID
     */
    private void setDueState(BaseHouseInfo beforeInfo, BaseHouseInfo afterInfo, String beforeRoomId, String afterRoomId) {
        // 查询调换前后两间房屋的 初缴金额+补缴金额-退款 的数目，调换后，与对应的应缴金额比较，判断是否为足额，修改相应的房间表数据
        //1，查询调换前房屋的总缴存你金额
        BigDecimal beforePayAmount = baseHouseInfoMapper.getPayAmount(beforeRoomId);
        beforePayAmount = beforePayAmount != null ? beforePayAmount : BigDecimal.ZERO;
        //2,查询调换后房屋的总缴存你金额
        BigDecimal afterPayAmount = baseHouseInfoMapper.getPayAmount(afterRoomId);
        afterPayAmount = afterPayAmount != null ? afterPayAmount : BigDecimal.ZERO;
        //3,查询调换前房间退款总金额
        BigDecimal beforeRefPayAmount = baseHouseInfoMapper.getRefPayAmount(beforeRoomId);
        //4,查询调换后房间退款总金额
        BigDecimal afterRefPayAmount = baseHouseInfoMapper.getRefPayAmount(afterRoomId);
        //调换前房间的总交存金额
        BigDecimal beforeAmount = beforePayAmount.subtract(beforeRefPayAmount != null ? beforeRefPayAmount : BigDecimal.ZERO);
        //调换后的房间的总交存金额
        BigDecimal afterAmount = afterPayAmount.subtract(afterRefPayAmount != null ? afterRefPayAmount : BigDecimal.ZERO);
        setValue(afterInfo, beforeAmount);
        setValue(beforeInfo, afterAmount);
    }

    /**
     * 设置交存状态
     *
     * @param houseInfo 房屋信息
     * @param amount    交存金额
     */
    public void setValue(BaseHouseInfo houseInfo, BigDecimal amount) {
        if (amount.compareTo(houseInfo.getFirstDue()) == 0) {
            houseInfo.setDueState(String.valueOf(NumberEnum.ONE.getNum()));
        } else if (amount.compareTo(houseInfo.getFirstDue()) > 0) {
            houseInfo.setDueState(String.valueOf(NumberEnum.TWO.getNum()));
        } else {
            houseInfo.setDueState(String.valueOf(NumberEnum.THREE.getNum()));
        }
    }

    /**
     * 需要修改的字段
     *
     * @param beforeInfo 调换前房屋信息
     * @param afterInfo  调换后房屋信息
     */
    private void setRoomParam(BaseHouseInfo beforeInfo, BaseHouseInfo afterInfo) {
        //银行编码
        String beforeInfoBankCode = beforeInfo.getBankCode();
        //余额
        BigDecimal beforeInfoFundBal = beforeInfo.getFundBal();
        //利息
        BigDecimal beforeInfoAccrBal = beforeInfo.getAccrBal();
        //计息日期
        String beforeInfoRateDate = beforeInfo.getRateDate();
        //结息类型
        Integer beforeInfoRateType = beforeInfo.getRateType();
        //在用利率
        BigDecimal beforeInfoAtRate = beforeInfo.getAtRate();
        //账户状态
        Integer beforeInfoAccState = beforeInfo.getAccState();
        //购房日期
        String beforeInfoPurchaseDate = beforeInfo.getPurchaseDate();

        //银行编码
        String afterInfoBankCode = afterInfo.getBankCode();
        //余额
        BigDecimal afterInfoFundBal = afterInfo.getFundBal();
        //利息
        BigDecimal afterInfoAccrBal = afterInfo.getAccrBal();
        //计息日期
        String afterInfoRateDate = afterInfo.getRateDate();
        //结息类型
        Integer afterInfoRateType = afterInfo.getRateType();
        //在用利率
        BigDecimal afterInfoAtRate = afterInfo.getAtRate();
        //账户状态
        Integer afterInfoAccState = afterInfo.getAccState();
        //购房日期
        String afterInfoPurchaseDate = afterInfo.getPurchaseDate();

        beforeInfo.setBankCode(afterInfoBankCode);
        beforeInfo.setFundBal(afterInfoFundBal);
        beforeInfo.setAccrBal(afterInfoAccrBal);
        beforeInfo.setRateDate(afterInfoRateDate);
        beforeInfo.setRateType(afterInfoRateType);
        beforeInfo.setAtRate(afterInfoAtRate);
        beforeInfo.setAccState(afterInfoAccState);
        beforeInfo.setPurchaseDate(afterInfoPurchaseDate);

        afterInfo.setBankCode(beforeInfoBankCode);
        afterInfo.setFundBal(beforeInfoFundBal);
        afterInfo.setAccrBal(beforeInfoAccrBal);
        afterInfo.setRateDate(beforeInfoRateDate);
        afterInfo.setRateType(beforeInfoRateType);
        afterInfo.setAtRate(beforeInfoAtRate);
        afterInfo.setAccState(beforeInfoAccState);
        afterInfo.setPurchaseDate(beforeInfoPurchaseDate);
    }

    @Override
    public BaseHouseInfo getInfo(String id) {
        return baseHouseInfoMapper.getInfo(id);
    }

    /**
     * 变更
     *
     * @param newBaseHouseInfo
     * @param modifyType
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult updateToSave(List<BaseHouseInfo> newBaseHouseInfo, String modifyType, String modifyCause) throws Exception {
        int num = newBaseHouseInfo.size();
        //房间id
        for (int i = 0; i < newBaseHouseInfo.size(); i++) {
            if (null != newBaseHouseInfo.get(i).getFlowInProgress() && !newBaseHouseInfo.get(i).getFlowInProgress().equals(NumStrEnum.ZERO.getNum())) {
                num = num - 1;
                newBaseHouseInfo.remove(i);
            }
        }
        List<String> id = new ArrayList<>();
        int no = 0;
        List<String> uuids = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            BaseHouseInfo baseHouseInfo = newBaseHouseInfo.get(i);
            if (StringUtils.isNotBlank(baseHouseInfo.getFirstMode())) {
                DepModeInfo d = depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
                if (d.getDepType().equals(NumStrEnum.ONE.getNum())) {
                    BaseOwnerInfo b = baseOwnerInfoMapper.getInfoByAccNo(baseHouseInfo.getId());
                    if (null != b) {
                        if (null == b.getPrice() || b.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先去业主变更维护" + baseHouseInfo.getRoomName() + "的售价");
                        }
                    }

                }
            }
            BaseHouseInfo newHouse = new BaseHouseInfo();
            BigDecimal f = baseHouseInfo.getStruArea();
            DecimalFormat df3 = new DecimalFormat("0.00");
            id.add(i, baseHouseInfo.getId());
            BaseHouseInfo oldHouse = baseHouseInfoMapper.getInfo(id.get(i));
            BaseOwnerInfo b = baseOwnerInfoMapper.getInfoByAccNo(baseHouseInfo.getId());
            if (null != b) {
                int countDep = depReqListInfoMapper.getCountByOwnerIdRun(oldHouse.getId(), b.getId());
                if (countDep > 0) {
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在在途缴存业务，不允许操作！");
                }
            }

            String uuid = UUIDUtil.getUUID();
            uuids.add(uuid);
            //todo
            BigDecimal str = new BigDecimal(df3.format(f));
            newHouse.setStruArea(str);
            newHouse.setOwnerId(oldHouse.getOwnerId());
            newHouse.setHouseAttrName(null);
            newHouse.setHouseAttr(baseHouseInfo.getHouseAttr());
            newHouse.setHouseUseName(null);
            newHouse.setCellName(oldHouse.getCellName());
            newHouse.setBuildName(oldHouse.getBuildName());
            newHouse.setRegionName(oldHouse.getRegionName());
            newHouse.setHouseSite(baseHouseInfo.getHouseSite());
            newHouse.setHouseUse(baseHouseInfo.getHouseUse());
            newHouse.setChange(oldHouse.getChange());
            newHouse.setFundBal(oldHouse.getFundBal());
            newHouse.setFirstModeName(oldHouse.getFirstModeName());
            newHouse.setOwnerNo(oldHouse.getOwnerNo());
            newHouse.setFirstDue(oldHouse.getFirstDue());
            newHouse.setFirstMode(baseHouseInfo.getFirstMode());
            newHouse.setRoomName(baseHouseInfo.getRoomName());
            newHouse.setOwnerName(oldHouse.getOwnerName());
            newHouse.setAccrBal(oldHouse.getAccrBal());
            newHouse.setDueState(oldHouse.getDueState());
            newHouse.setAccountFrozen(oldHouse.getAccountFrozen());
            if (oldHouse.getAccountFrozen().compareTo(BigDecimal.ZERO) == 0) {
                newHouse.setAccountFrozen(new BigDecimal("0.00"));
            }
            newHouse.setPrice(oldHouse.getPrice());
            //保存变更表
            no = modifyUtil.updateToSave(oldHouse, newHouse, id.get(i), modifyType, modifyCause, uuid);
            //绑定审批流
            if (no <= 0) {
                continue;
            }
            String initState = flowUpdateAuditUtil.initFlow(id.get(i), uuid, modifyType, null);
            //当返回通过时表明该记录不需要审核，直接更新到业务表
            if (FlowStateEnum.PASS.getState().equals(initState)) {
                //查询数据库原数据
                BaseHouseInfo info = baseHouseInfoMapper.getInfo(id.get(i));
                updateHouseSite(newHouse, info);
                //变更值合并到原数据   注意参数：uuid变更类型id   info数据库实体
                BaseHouseInfo houseInfo = modifyUtil.getCompleteEntity(uuid, info);
                //全表更新
                no = baseHouseInfoMapper.updateById(baseOwnerInfoService.changeFirst(houseInfo));
                if (no == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                }
            }
        }
        for (String uuid : uuids) {
            int baseModifyDetails = baseModifyDetailMapper.selectCountByReqNo(uuid);
            if (baseModifyDetails == 0) {
                continue;
            } else {
                return CommonResult.ResponseResult(1);
            }
        }
        return CommonResult.ResponseResult(0, "请添加变更数据再提交");
    }

    private int updateHouseSite(BaseHouseInfo baseHouseInfo, BaseHouseInfo info) {
        int num = 1;
        //修改房屋
        String subRegionName = "";
        BaseHouseInfo b = baseHouseInfoMapper.getInfo(info.getId());
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(b.getBuildNo());
        if (StringUtils.isNotBlank(baseBuildInfo.getSubRegionNo())) {
            BaseSubRegionInfo baseSubRegionInfo = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo());
            subRegionName = baseSubRegionInfo.getSubRegionName();
        }
        BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(b.getCellNo());
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(info.getZoneCode(), 0, 4));
        String houseSite = zoneName + baseRegionInfo.getRegionName() + subRegionName + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + baseHouseInfo.getRoomName();
        if (!baseHouseInfo.getRoomName().equals(info.getRoomName())) {
            num = baseHouseInfoMapper.updateHouseSite(houseSite, info.getId());
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        return num;
    }
}
